/**
 *@NApiVersion 2.x
 *@NScriptType Suitelet
 */
define(['N/ui/serverWidget', 'N/record', 'N/task'], function (ui, record, task) {
    function onRequest(context) {
        try {
            var form = ui.createForm({
                title: '正在更新制造费用,请勿重复更新!'
            });
            context.response.writePage(form);
            var recId = context.request.parameters.recid;
            record.submitFields({
                type: 'customrecord_monthmanufactureexpense',
                id: recId,
                values: {
                    custrecord_enable_update: true
                }
            });
            updateManufacturefee(recId,context);

        } catch (e) {
            log.debug('e', JSON.stringify(e));
        }
    }

    function updateManufacturefee(recId,context) {
        log.debug('updateManufacturefee start', 'updateManufacturefee start');
        try {
            var mrTask = task.create({taskType: task.TaskType.MAP_REDUCE});
            mrTask.scriptId = 'customscript_mr_update_manufacturefee';

            //mrTask.deploymentId = 'customdeploy_mr_update_manufacturefee';
            var mrTaskId = mrTask.submit();
            var taskStatus = task.checkStatus(mrTaskId);

            for (; ;) {
                 taskStatus = task.checkStatus(mrTaskId);
                if (taskStatus.stage === task.MapReduceStage.REDUCE) {
                    var needUpdateCount = taskStatus.getPendingMapCount();
                    log.debug('map completed','');

                    var form = ui.createForm({
                        title: '已成功更新制造费用!'+needUpdateCount
                    });
                    context.response.writePage(form);
                    break;
                }

            }

        } catch (e) {

        }

        log.debug('updateManufacturefee end', 'success!');

    }

    return {
        onRequest: onRequest
    };
});